using System;
using System.Collections.Generic;
using System.Text;
using NBusiness.CodeDom.Compiler;
using NBusiness.ESharp.Compiler;
using NBusiness.CodeDom;
using System.IO;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using Microsoft.VisualBasic;
using System.CodeDom;

namespace NBusiness.Templates
{
    public abstract class TemplateBase : ITemplate
    {
        protected EntityResourceFile GenerateFile(PartialLanguage partialLanguage, CodeCompileUnit unit, string fileName)
        {
            StringWriter sw = new StringWriter();
            CodeGeneratorOptions op = new CodeGeneratorOptions();
            CodeDomProvider provider = null;
            switch (partialLanguage)
            {
                case PartialLanguage.CS:
                    provider = new CSharpCodeProvider();
                    op.BracingStyle = "C";
                    op.ElseOnClosing = false;
                    break;
                case PartialLanguage.VB:
                    provider = new VBCodeProvider();
                    break;
            }
            op.BlankLinesBetweenMembers = false;
            op.IndentString = "\t";
            op.VerbatimOrder = true;
            provider.GenerateCodeFromCompileUnit(unit, sw, op);

            string code = sw.GetStringBuilder().ToString();
            byte[] data = Encoding.UTF8.GetBytes(code);

            EntityResourceFile file = new EntityResourceFile(
                fileName,
                EntityBuildAction.Compile);
            file.Data = data;

            return file;
        }

        public abstract EntityResourceFile[] Generate(PartialLanguage partialLanguage, params Entity[] entities);

        #region Warning
        public event EventHandler<EntityBuildErrorEventArgs> Warning;
        protected virtual void OnWarning(ESharpBuildWarning warning)
        {
            if (Warning != null) Warning(this, new EntityBuildErrorEventArgs(warning));
        }
        #endregion
    }
}
